<?php
/**
 * Created by PhpStorm.
 * User: liyan
 * Date: 2019/2/26
 * Time: 17:48
 */

namespace app\m\controller;

use think\Db;

class Msg
{
    public function msg_list()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $list = [];
        $now = $_SERVER['REQUEST_TIME'];
        $today = strtotime(date('Y-m-d', $now));    //获得今日时间戳
        $year = strtotime(date('Y'), $now);        //获得今年时间戳
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $type = isset($_GET['type']) ? intval($_GET['type']) : 1;      //0 消息通知， 1私信消息
        $m = $_GET['m'] ? intval($_GET['m']) : 0;
        $where = '';
        if ($type) {
            //取出所有关联用户房间id
            $qs = DB::query('select r.id,r.last_msg,r.read,r.mread,r.time,u.uid,u.name,u.avatar,m.uid muid,m.name mname,m.avatar mavatar from x1_msg_room r left join x1_user u on r.uid=u.uid  left join x1_user m on r.muid=m.uid where (r.uid=? or (r.uid!=0 and r.muid=?)) order by time desc', [$uid, $uid]);
            if ($qs) {
                $user = [];
                $read = 0;   //未读
                foreach ($qs as $v) {
                    if ($v['muid'] == $uid) {
                        $user = ['uid' => $v['uid'], 'name' => $v['name'], 'avatar' => $v['avatar'] ? $v['avatar'] : 'https://c.g56.cn/x9/user_im.png'];
                        $read = $v['mread'];
                    } else {
                        $user = ['uid' => $v['muid'], 'name' => $v['mname'], 'avatar' => $v['mavatar'] ? $v['avatar'] : 'https://c.g56.cn/x9/user_im.png'];
                        $read = $v['read'];
                    }
                    if($v['last_msg']){
                        $item = json_decode($v['last_msg'], true);
                        $item['user'] = $user;
                        $item['read'] = $read;
                        if ($item['time'] >= $today) {
                            $format = 'H:i';
                        } elseif ($item['time'] >= $year) {
                            $format = 'm-d';
                        } else {
                            $format = 'y-m-d';
                        }
                        $item['time_format'] = date($format, $item['time']);
                    }else{
                        $item = ['user'=>$user,'read'=>$read,'pid'=>$v['id']];
                    }
                    $list[] = $item;
                }
            }
        } else {
            if ($m && $id) {
                $where = ' and s.id <' . $id;
            }
            $qs = DB::query('select s.id,s.pid,s.title,s.content,s.type,s.time,s.behave,s.read_time,r.mread,u.uid,u.name,u.avatar from x1_msg_room r left join x1_msg s on r.id=s.pid left join x1_user u on s.uid=u.uid where r.uid=0 and r.muid=? ' . $where . ' order by s.id desc', [$uid]);
            if ($qs) {
                $user = [];
                $default = ['uid' => 0, 'name' => '系统', 'avatar' => 'https://c.g56.cn/x9/user_im.png'];
                foreach ($qs as $v) {
                    $read = $v['mread'];
                    $item = $v;
                    $item['read'] =$read;
                    $item['user'] = $default;
                    if ($item['time'] >= $today) {
                        $format = 'H:i';
                    } elseif ($item['time'] >= $year) {
                        $format = 'm-d';
                    } else {
                        $format = 'y-m-d';
                    }
                    $item['time_format'] = date($format, $item['time']);
                    unset($item['mread']);
                    $list[] = $item;
                }
            }
        }
        echo json_encode(['err' => 0, 'msg' => '获取消息列表成功', 'list' => $list]);
    }

    public function msg_detail()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $pid = intval($_GET['pid']);
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $m = isset($_GET['m']) ? intval($_GET['m']) : 0;
        $now = $_SERVER['REQUEST_TIME'];
        $qs = Db::query('select uid,muid,last_msg,`read`,mread from x1_msg_room where id=?', [$pid]);
        $sender = [];
        $last_msg = [];
        if ($qs) {
            $last_msg = json_decode($qs[0]['last_msg'], true);
            $read = $qs[0]['uid'] == $uid ? $qs[0]['read'] : $qs[0]['mread']; //当前用户阅读数量
            $muid = $qs[0]['uid'] == $uid ? $qs[0]['muid'] : $qs[0]['uid'];
            if ($muid) {
                $qs = Db::query('select uid,name,avatar from x1_user where uid=?', [$muid]);
                if (!$qs) {
                    echo '{"err":1001,"msg":"联系人无法找到"}';
                    return;
                }
                $sender = $qs[0];
                $sender['avatar'] = $sender['avatar'] ? $sender['avatar'] : 'https://c.g56.cn/x9/user_im.png';
            } else {
                $sender = ['uid' => 0, 'name' => '系统通知', 'avatar' => 'https://c.g56.cn/x9/user_im.png'];
            }
            Db::query('update x1_msg set read_time=? where pid=? and uid=? and read_time=0', [$now, $pid, $uid]);
            if ($last_msg['uid'] == $uid && $last_msg['read_time'] == 0 || $read != 0) {
                if ($last_msg['uid'] == $uid && $last_msg['read_time'] == 0) {
                    $last_msg['read_time'] = $now;
                }
                if ($muid > $uid) {
                    Db::execute('update x1_msg_room set `read`=?,last_msg=? where id=?', [0, json_encode($last_msg), $pid]);
                } else {
                    Db::execute('update x1_msg_room set mread=?,last_msg=? where id=?', [0, json_encode($last_msg), $pid]);
                }
            }
        }
        $qs = Db::query('select uid,name,avatar from x1_user where uid=?', [$uid]);
        $user = $qs[0];
        $user['avatar'] = $user['avatar'] ? $user['avatar'] : 'https://c.g56.cn/x9/user_im.png';

        if ($m && $id) {
            $qs = Db::query('select id,uid,sender,time,read_time,title,content from  x1_msg  where pid=? and id<? limit 0,20', [$pid, $id]);
            if (count($qs) == 20) {
                $len = count($qs);
                $min_id = $qs[$len - 1]['id'];
                $cr = Db::query('select count(*) num from x1_msg where  pid=? and id<?', [$pid, $min_id]);
                $count = $cr[0]['num'];
                if ($count) {
                    $more = 1;
                } else {
                    $more = 0;
                }
            } else {
                $min_id = $id;
                $more = 0;
            }
        } else {
            $qs = Db::query('select id,uid,sender,time,read_time,title,content from  x1_msg  where pid=? limit 0,20', [$pid]);
            if (count($qs) == 20) {
                $len = count($qs);
                $min_id = $qs[$len - 1]['id'];
                $cr = Db::query('select count(*) num from x1_msg where pid=? and id<=', [$pid, $min_id]);
                $count = $cr[0]['num'];
                if ($count) {
                    $more = 1;
                } else {
                    $more = 0;
                }
            } else {
                $min_id = $id;
                $more = 0;
            }
        }

        $list = [];
        foreach ($qs as $v) {
            $v['time'] = date('y-m-d H:i', $v['time']);
            $v['is_read'] = $v['read_time'] ? 0 : 1;    //1 未读，1已读
            if ($v['sender'] == $uid) {
                $v['user'] = $user;
                $v['is_sender'] = 0;
            } else {
                $v['user'] = $sender;
                $v['is_sender'] = 1;
            }
            $list[] = $v;
        }
        $list = array_values($list);
        //更新已读消息
        echo json_encode(['err' => 0, 'msg' => '获取消息成功', 'list' => $list, 'user' => $sender, 'more' => $more]);
    }


    //消息通知详情
    public function msg_notice(){
        $ses=session('ses');
        $id=isset($_GET['id'])?intval($_GET['id']):0;
        if(!$ses || !$id){
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $qs=Db::query('select id,title,content,time,behave from x1_msg where id=?',[$id]);
        if(!$qs){
            echo '{"err":1001,"msg":"这条消息不存在"}';
            return;
        }
        $msg=$qs[0];
        $msg['time']=date('Y-m-d H:i',$msg['time']);
        $now=time();
        Db::execute('update x1_msg set read_time=? where id=?',[$now, $id]);
        echo json_encode(['err'=>0,'msg'=>'获取消息通知成功','message'=>$msg]);
    }

    //寻找联系人
    public function search_contact()
    {
        $keywords = $_GET['keywords'];
        $ses = session('ses');
        if (!$ses || !$keywords) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $list = Db::table('x1_user')->field('uid,name,avatar')->where('name', 'like', ':name')->bind(['name' => "%{$keywords}%"])->where('uid', 'neq', $uid)->limit(0, 20)->select();
        echo json_encode(['err' => 0, 'msg' => '查找联系人成功', 'list' => $list]);
    }

    //发送私人信息
    public function send_msg()
    {
        $ses = session('ses');
        if (!$ses) {
            echo '{"err":1,"msg":"param error"}';
            return;
        }
        $uid = $ses['uid'];
        $pid = $_GET['pid'];
        $title = isset($_GET['title']) ? addslashes($_GET['title']) : '';
        $content = addslashes($_GET['msg']);
        $type = isset($_GET['type']) ? intval($_GET['type']) : 1;
        $behave = isset($_GET['behave']) ? addslashes($_GET['behave']) : '';
        $now = $_SERVER['REQUEST_TIME'];
        if (empty($content)) {
            echo '{"err":1001,"msg":"param error1"}';
            return;
        }
        //相同消息3s内不再发送
        $qs = Db::query('select id,pid,time,title,content,uid,sender from x1_msg where pid=? and type=?', [$pid, $type]);
        if ($qs) {
            $msg = $qs[0];
            $sender = $uid == $msg['uid'] ? $msg['sender'] : $msg['uid'];
            if ($now - $qs[0]['time'] < 3) {

                $msg['time'] = date('y-m-d H:i', $msg['time']);
                echo json_encode(['err' => 1001, 'msg' => '您发送的太频繁了，请休息一下在发送']);
                return;
            }
        } else {
            $qs = Db::query('select uid,muid from x1_msg_room where id=?', [$pid]);
            if (!$qs) {
                echo json_encode(['err' => 1002, 'msg' => '对话房间不存在']);
                return;
            }
            $sender = $uid == $qs[0]['uid'] ? $qs[0]['muid'] : $qs[0]['uid'];
        }
        //创建
        $qs = Db::query('select id from x1_msg_room where (uid=? and muid=?) or (uid=? and muid=?)', [$uid, $sender, $sender, $uid]);
        if (!$qs) {
            $data = ['time' => $now, 'state' => 1, 'mstate' => 1, 'uid' => $uid, 'muid' => $sender, 'last_msg' => ''];
            if ($sender < $uid) {
                $data['uid'] = $sender;
                $data['muid'] = $uid;
            }
            $room_id = Db::table('x1_msg_room')->insertGetId($data);
        } else {
            $room_id = $qs[0]['id'];
        }

        $data = ['uid' => $sender, 'sender' => $uid, 'pid' => $room_id, 'title' => $title, 'content' => $content, 'time' => $now, 'read_time' => 0, 'behave' => '', 'type' => $type, 'state' => 0];
        $id = Db::table('x1_msg')->insertGetId($data);
        Db::query('update x1_msg_room set last_msg=? where id=?', [json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), $room_id]);
        $msg = $data;
        $msg['id'] = $id;
        $msg['time'] = date('y-m-d H:i', $msg['time']);
        $msg['is_sender'] = 0;
        $qs=Db::query('select name,avatar from x1_user where uid=?',[$uid]);
        if(!$qs){
            echo '{"err":1003,"msg":"用户信息不存在"}';
            return;
        }
        $msg['user']=$qs[0];
        $msg['user']['uid']=$uid;
        $msg['user']['avatar']=$msg['user']['avatar']?$msg['user']['avatar']:'https://c.g56.cn/x9/user_im.png';
        unset($msg['state']);
        unset($msg['type']);
        echo json_encode(['err' => 0, 'msg' => '发送成功', 'data' => $msg]);
        return;
    }

}